package pl.enigmatic.parser.string.java.awt;

import java.awt.Color;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;

import pl.enigmatic.parser.string.Converter;


public class ColorConverter extends Converter<Color> {

	private static final String HASH = "#";
	private static final HashMap<String, Color> predefined = new HashMap<String, Color>();
	static {
		for (final Field field : Color.class.getDeclaredFields()) {
			if (Modifier.isStatic(field.getModifiers()) && Modifier.isPublic(field.getModifiers()) && field.getType().equals(Color.class)) {
				try {
					predefined.put(field.getName().toLowerCase(), (Color) field.get(null));
				} catch (final Exception e) {}
			}
		}
	}

	/**
	 */
	@Override
	public Color convert(final String value) {
		Color res = Color.BLACK;
		if (value != null && !value.equals("")) {
			final String split[] = value.split(":");
			if (predefined.containsKey(split[0])) {
				res = predefined.get(split[0]);
				if (split.length > 1) {
					res = new Color(res.getRed(), res.getGreen(), res.getBlue(), Integer.parseInt(split[1], 16));
				}
			} else if (value.startsWith(HASH)) {
				if (value.length() == 9) {
					res = Color.decode(HASH + value.substring(3, 9));
					res = new Color(res.getRed(), res.getGreen(), res.getBlue(), Integer.parseInt(value.substring(1, 3), 16));
				} else if (value.length() == 7) {
					res = Color.decode(value);
				}
			}
		}
		return res;
	}

	@Override
	public String convertBack(final Color value) {
		return HASH + Integer.toHexString(value.getRGB());
	}
}
